<template>
  <div class="charge-order-manage">
    <div style="display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 20px;">
      <h2>订单管理</h2>
      <el-button type="primary" @click="goToCreateOrder">创建新订单</el-button>
    </div>

    <!-- 筛选表单 -->
    <el-form :inline="true" :model="queryForm" class="mb-4">
      <el-form-item label="订单编号">
        <el-input v-model="queryForm.orderNo" placeholder="请输入订单编号" />
      </el-form-item>
      <el-form-item label="用户ID">
        <el-input v-model.number="queryForm.userId" placeholder="请输入用户ID" />
      </el-form-item>
      <el-form-item label="充电桩编号">
        <el-input v-model="queryForm.pileName" placeholder="请输入充电桩编号" />
      </el-form-item>
      <el-form-item label="支付状态">
        <el-select v-model="queryForm.payStatus" placeholder="全部">
          <el-option label="未支付" value="0" />
          <el-option label="已支付" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="充电时间">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchOrderList">筛选</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单表格 -->
    <el-table :data="tableData" border style="width: 100%" ref="orderTable">
      <el-table-column prop="orderNo" label="订单编号" width="180" />
      <el-table-column prop="userName" label="用户名称" />
      <el-table-column prop="pileName" label="充电桩编号" />
      <el-table-column prop="pileLocation" label="充电地点" />
      <el-table-column prop="startTime" label="开始时间">
        <template #default="scope">
          {{ formatDateTime(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间">
        <template #default="scope">
          <span v-if="scope.row.endTime">{{ formatDateTime(scope.row.endTime) }}</span>
          <span v-else class="text-warning">充电中</span>
        </template>
      </el-table-column>
      <el-table-column label="充电时长">
        <template #default="scope">
          {{ calculateDuration(scope.row.startTime, scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="powerUsed" label="充电量(kWh)" :formatter="(row) => row.powerUsed.toFixed(2)" />
      <el-table-column prop="unitPrice" label="单价(元/kWh)" />
      <el-table-column prop="totalAmount" label="总费用(元)" :formatter="(row) => row.totalAmount.toFixed(2)" />
      <el-table-column prop="payStatus" label="支付状态">
        <template #default="scope">
          <el-tag v-if="scope.row.payStatus === 0" type="warning">未支付</el-tag>
          <el-tag v-else type="success">已支付</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="payTime" label="支付时间">
        <template #default="scope">
          {{ scope.row.payTime ? formatDateTime(scope.row.payTime) : '未支付' }}
        </template>
      </el-table-column>
      <el-table-column prop="payType" label="支付方式" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" @click="viewDetail(scope.row)">详情</el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="goToPay(scope.row)"
            v-if="scope.row.payStatus === 0 && scope.row.endTime"
          >
            支付
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="cancelOrder(scope.row.id)"
            v-if="scope.row.payStatus === 0 && !scope.row.endTime"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange"
      :current-page="queryForm.pageNum" 
      :page-sizes="[10, 20, 50]" 
      :page-size="queryForm.pageSize" 
      :total="total"
      layout="total, sizes, prev, pager, next, jumper" 
      style="margin-top: 20px; text-align: right;"
    />

    <!-- 订单详情弹窗 -->
    <el-dialog :visible.sync="detailVisible" title="订单详情" width="60%" :close-on-click-modal="false">
      <el-descriptions :column="2" border :title="`订单编号：${orderDetail.orderNo}`">
        <el-descriptions-item label="用户信息">
          {{ orderDetail.userName }}（ID：{{ orderDetail.userId }}）
        </el-descriptions-item>
        <el-descriptions-item label="充电桩信息">
          {{ orderDetail.pileName }}（{{ orderDetail.pileLocation }}）
        </el-descriptions-item>
        <el-descriptions-item label="充电开始时间">{{ formatDateTime(orderDetail.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="充电结束时间">{{ orderDetail.endTime ? formatDateTime(orderDetail.endTime) : '充电中' }}</el-descriptions-item>
        <el-descriptions-item label="充电时长">{{ calculateDuration(orderDetail.startTime, orderDetail.endTime) }}</el-descriptions-item>
        <el-descriptions-item label="充电量">{{ orderDetail.powerUsed ? orderDetail.powerUsed.toFixed(2) + ' kWh' : '-' }}</el-descriptions-item>
        <el-descriptions-item label="电价规则">
          <span v-if="orderDetail.priceRule">峰谷电价（{{ orderDetail.priceRule }}）</span>
          <span v-else>默认电价</span>
        </el-descriptions-item>
        <el-descriptions-item label="单价">{{ orderDetail.unitPrice }} 元/kWh</el-descriptions-item>
        <el-descriptions-item label="总费用" :span="2">
          <span class="amount">{{ orderDetail.totalAmount ? orderDetail.totalAmount.toFixed(2) + ' 元' : '0.00 元' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <el-tag v-if="orderDetail.payStatus === 0" type="warning">未支付</el-tag>
          <el-tag v-else type="success">已支付</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ orderDetail.payTime ? formatDateTime(orderDetail.payTime) : '未支付' }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ orderDetail.payType || '未支付' }}</el-descriptions-item>
        <el-descriptions-item label="订单创建时间">{{ formatDateTime(orderDetail.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 支付弹窗 -->
    <el-dialog :visible.sync="payVisible" title="订单支付" width="40%" :close-on-click-modal="false">
      <el-form :model="payForm" label-width="100px">
        <el-form-item label="订单编号">
          <el-input v-model="payForm.orderNo" disabled />
        </el-form-item>
        <el-form-item label="应付金额">
          <el-input v-model="payForm.totalAmount" disabled prefix="¥" />
        </el-form-item>
        <el-form-item label="支付方式" prop="payType">
          <el-radio-group v-model="payForm.payType">
            <el-radio label="微信支付"><i class="el-icon-wechat"></i> 微信支付</el-radio>
            <el-radio label="支付宝支付"><i class="el-icon-alipay"></i> 支付宝支付</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="payVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPay">确认支付</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ChargeOrderManage',
  data() {
    return {
      // 查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        orderNo: '',
        userId: null,
        pileName: '',  // 改为pileName
        payStatus: null,
        startTimeBegin: null,
        startTimeEnd: null
      },
      dateRange: [],
      tableData: [],
      total: 0,
      // 弹窗状态
      detailVisible: false,
      payVisible: false,
      orderDetail: {},
      payForm: {
        orderId: null,
        orderNo: '',
        totalAmount: 0,
        payType: '微信支付'
      }
    }
  },
  mounted() {
    this.fetchOrderList()
  },
  methods: {
    // 跳转到订单生成页
    goToCreateOrder() {
      this.$router.push('/order/create-order') // 需配置路由
    },
    // 获取订单列表
    async fetchOrderList() {
      const loading = this.$loading({ lock: true, text: '加载订单中...', spinner: 'el-icon-loading' })
      try {
        // 处理日期范围
        if (this.dateRange.length === 2) {
          this.queryForm.startTimeBegin = this.dateRange[0]
          this.queryForm.startTimeEnd = this.dateRange[1]
        } else {
          this.queryForm.startTimeBegin = null
          this.queryForm.startTimeEnd = null
        }

        const response = await request({
          url: '/order/pageList',
          method: 'get',
          params: this.queryForm
        })

        if (response.code === 200) {
          this.tableData = response.data.records || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.data.msg || '获取订单失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error(error.response?.data?.msg || '网络错误')
      } finally {
        loading.close()
      }
    },
    // 重置筛选
    resetQuery() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 10,
        orderNo: '',
        userId: null,
        pileName: '',  // 改为pileName
        payStatus: null,
        startTimeBegin: null,
        startTimeEnd: null
      }
      this.dateRange = []
      this.fetchOrderList()
    },
    // 分页相关
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchOrderList()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.fetchOrderList()
    },
    // 查看订单详情
    async viewDetail(row) {
      const loading = this.$loading({ lock: true, text: '加载详情中...', spinner: 'el-icon-loading' })
      try {
        const response = await request({
          url: `/order/getOrder/${row.id}`,
          method: 'get'
        })
        if (response.code === 200) {
          this.orderDetail = response.data
          this.detailVisible = true
        } else {
          this.$message.error(response.data.msg || '获取详情失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error(error.response?.data?.msg || '网络错误')
      } finally {
        loading.close()
      }
    },
    // 前往支付
    goToPay(row) {
      this.payForm = {
        orderId: row.id,
        orderNo: row.orderNo,
        totalAmount: row.totalAmount,
        payType: '微信支付'
      }
      this.payVisible = true
    },
    // 确认支付
    async confirmPay() {
      if (!this.payForm.orderId) {
        return this.$message.error('订单信息异常')
      }

      const loading = this.$loading({ lock: true, text: '支付中...', spinner: 'el-icon-loading' })
      try {
        const response = await request({
          url: '/order/payOrder',
          method: 'post',
          data: {
            orderId: this.payForm.orderId,
            payType: this.payForm.payType,
            payTime: new Date().toISOString()
          }
        })

        if (response.code === 200) {
          this.$message.success('支付成功')
          this.payVisible = false
          this.fetchOrderList()
        } else {
          this.$message.error(response.data.msg || '支付失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error(error.response?.data?.msg || '支付失败')
      } finally {
        loading.close()
      }
    },
    // 取消订单（仅充电中未支付订单可取消）
    async cancelOrder(orderId) {
      try {
        await this.$confirm('确定要取消该订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const loading = this.$loading({ lock: true, text: '取消中...', spinner: 'el-icon-loading' })
        try {
          const response = await request({
            url: `/order/cancelOrder/${orderId}`,
            method: 'put'
          })

          if (response.code === 200) {
            this.$message.success('订单已取消')
            this.fetchOrderList()
          } else {
            this.$message.error(response.data.msg || '取消失败')
          }
        } catch (error) {
          console.error(error)
          this.$message.error(error.response?.data?.msg || '取消失败')
        } finally {
          loading.close()
        }
      } catch (cancel) {
        this.$message.info('已取消操作')
      }
    },
    // 导出订单报表
    async exportOrderList() {
      const loading = this.$loading({ lock: true, text: '导出中...', spinner: 'el-icon-loading' })
      try {
        // 构建查询参数
        const params = new URLSearchParams()
        Object.keys(this.queryForm).forEach(key => {
          if (this.queryForm[key] !== null && this.queryForm[key] !== undefined) {
            params.append(key, this.queryForm[key])
          }
        })

        // 日期范围
        if (this.dateRange.length === 2) {
          params.append('startTimeBegin', this.dateRange[0])
          params.append('startTimeEnd', this.dateRange[1])
        }

        // 下载文件（后端返回Excel流）
        const response = await request({
          url: '/order/exportOrder',
          method: 'get',
          params: params,
          responseType: 'blob' // 关键：接收二进制流
        })

        // 处理下载
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const fileName = `订单报表_${new Date().getTime()}.xlsx`
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(link.href)

        this.$message.success('导出成功')
      } catch (error) {
        console.error(error)
        this.$message.error(error.response?.data?.msg || '导出失败')
      } finally {
        loading.close()
      }
    },
    // 格式化日期时间显示 (改为 年月日 时分)
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      
      const date = new Date(dateTime)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    // 根据开始和结束时间计算充电时长
    calculateDuration(startTime, endTime) {
      if (!startTime) return '-'
      if (!endTime) return '充电中'
      
      const start = new Date(startTime).getTime()
      const end = new Date(endTime).getTime()
      const seconds = Math.floor((end - start) / 1000)
      
      // 格式化时长为 时:分:秒
      const h = Math.floor(seconds / 3600).toString().padStart(2, '0')
      const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0')
      const s = (seconds % 60).toString().padStart(2, '0')
      
      return `${h}:${m}:${s}`
    }
  }
}
</script>

<style scoped>
.charge-order-manage {
  padding: 20px;
}

.text-warning {
  color: #faad14;
}

.amount {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: 600;
}

.el-descriptions-item__label {
  font-weight: 500 !important;
}
</style>